#include "debug.h"

#include <stdio.h>
#include <stdint.h>


#include <avr/pgmspace.h>
FILE usart_str = FDEV_SETUP_STREAM(usart_putchar, NULL, _FDEV_SETUP_WRITE);

/****************************************************************************
* Purpose:	putchar funtion used to allow stdio redirection. Writes a single
*			char to debug serial port
* Input:	char to be written and the file stream to write the file
* Output:   Always returns 0, return value is to comply with functptr type
****************************************************************************/
int usart_putchar(char c, FILE *stream)
{
	USARTF0.DATA = c;

	// Wait for tx to complete
	if(!(USARTF0.STATUS & USART_DREIF_bm))
	{
		while(!(USARTF0.STATUS & USART_TXCIF_bm));
	}

	// clear TX interrupt flag
	USARTF0.STATUS |= USART_TXCIF_bm;

	return 0;
}

/****************************************************************************
* Purpose:	Initializes debug serial port
* Input:	No Input
* Output:   No Output
****************************************************************************/
void debugInit()
{
	// Enable Async USART at 19200 Baud
	USARTF0.BAUDCTRLA = 103;
	USARTF0.BAUDCTRLB = 0;

	// Set Tx pin as output
	PORTF.DIR |= (1<<3);

	// Initially set Tx high...otherwise the port can hang (according to bostongandroid.org)
	PORTF.OUT |= (1<<3);

	/*zero control registers*/
	USARTF0_CTRLA = 0x00;
	USARTF0_CTRLB = 0x00;
	USARTF0_CTRLC = 0x00;

	// Set in Async, Non-duplex mode-----can't think of the right work (8b-1stopbit-noparity)
	USARTF0_CTRLC = 0b00000011;

	// enable tx and rx on USART
	USARTF0.CTRLB = USART_TXEN_bm | USART_RXEN_bm;

	USARTF0_CTRLA = 0b00000000;

	// Redirect stdio to point to our usart_str file stream
	stdout = &usart_str;
}